# 静态化页面
from apps.contents.models import GoodsChannel,ContentCategory
from django.conf import settings
from django.template import loader
import os

def generate_static_index_html():
    categories = {}

    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category
        categories[group_id]['channels'].append({
            'id': channel.id,
            'name': cat1.name,
            'url': channel.url
        })

        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    contents = {}
    content_categories = ContentCategory.objects.all()
    for contest_cat in content_categories:
        contents[contest_cat.key] = contest_cat.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories': categories,
        'contents': contents
    }

    templates = loader.get_template('index.html')
    html_str = templates.render(context)

    file_path = os.path.join(os.path.dirname(os.path.dirname(settings.BASE_DIR)),'front_end_pc/index.html')
    with open(file_path,'w',encoding='utf-8') as f:
        f.write(html_str)

